// pages/login/login.js
let api = require("../../mars/services/api.js");
let that;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    groupId: "",
    //  inviterName:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    let user = wx.getStorageSync("user");
    let groupId = options.groupId;
    //  let inviterName = options.inviterName;

    if (groupId) {
      that.setData({
        groupId: groupId,
        //  inviterName: inviterName
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  joinInGroup(groupId) {
    api.WxRequest(api.partInGroup, {
      groupId: groupId,
      userId: wx.getStorageSync('user').id
    }, (res) => {
      console.log('invite over!!!', res);
      if (res.status) return;
      wx.showToast({
        title: '已接受邀请,加入小组',
        icon: "none"
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    });
  },
  getUserInfo(e) {
    let userInfo = e.detail;
    wx.login({
      success: function(res) {
        if (res.code) {
          //发起网络请求
          console.log(res.code);
          api.WxRequest(api.checkIsNew, {
            code: res.code,
            userInfo: userInfo.userInfo
          }, (res) => {
            wx.setStorageSync('user', res.data); //存储openid 

            if (that.data.groupId) {
              console.log('invited');
              that.joinInGroup(that.data.groupId);
            } else {
              wx.navigateBack();
            }
          });
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  }
})